<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Gallery_model extends MY_Model {

    function __construct() {
        parent::__construct("gallery_item", "id", Array(
            "image_id" => "Image_model",
                //"video_id" => "Video_model"
        ));
        $this->delAttribute = "is_deleted";
    }

    protected function read($where = Array(), $fetchForeign = false, $depth = 1, $page = -1, $limit = 10) {
        $results = parent::read($where, $fetchForeign, $depth, $page, $limit);
        $userId = $this->curUserId();

        foreach ($results as $result) {
            $result->points = 0;
            $sqlp = "SELECT SUM( POINT ) AS points FROM gallery_vote WHERE gallery_vote.gallery_id = " . $result->id . " GROUP BY gallery_id";
            foreach ($this->db->query($sqlp)->result() as $row) {
                $result->points += $row->points;
            }

            $result->vote = 0;
            $sqlp = "SELECT point FROM gallery_vote WHERE gallery_id = " . $result->id . " AND user_id = " . $userId;
            foreach ($this->db->query($sqlp)->result() as $row) {
                $result->vote += $row->point;
            }

            $result->poster_id = 0;

            switch ($result->type) {
                case "IMG" :
                    $imgObj = null;
                    if (is_object($result->image_id)) {
                        $imgObj = $result->image_id;
                    } else {
                        $this->load->model("Image_model");
                        $imgObj = $this->Image_model->findById($result->image_id, true, 1);
                    }
                    if ($imgObj != null) {
                        $postedArr = explode(" ", $imgObj->uploaded);
                        $result->posted_date = $postedArr[0];
                        $result->posted_time = $postedArr[1];
                        $result->judul = $imgObj->caption;
                        $result->src = $imgObj->src;
                        $result->tmb = $imgObj->tmb;
                        $result->poster_id = $imgObj->uploader_id;
                    }
                    $result->jenis = "Gambar";
                    break;
                case "VID" :
                    $result->jenis = "Video";
                    break;
            }

            $this->load->model("User_model");
            $posterObj = $this->User_model->findById($result->poster_id);
            $result->poster_name = $posterObj->display_name;
        }

        return $results;
    }

    public function createImage($type, $imgFile, $imgCaption) {
        $this->load->model("User_model");
        $curUserId = $this->curUserId();
        $roles = $this->User_model->fetchRoles($curUserId);
        $isAdmin = in_array("gal_auditor", $roles);
        $this->load->model("Image_model");
        $imgId = $this->Image_model->create($imgFile, $imgCaption, Array());
        if ($imgId > 0) {
            return parent::create(Array(
                        "type" => $type,
                        "is_approved" => $isAdmin,
                        "approved" => ($isAdmin ? date("Y-m-d H:i:s") : null),
                        "is_featured" => 0,
                        "image_id" => $imgId
            ));
        }
    }

    public function fetchHL($page = 0, $perPage = 5) {
        $this->orders = Array(
            Array(
                "by" => "approved",
                "opt" => "desc"
            )
        );
        return $this->findAll(Array(
                    "is_approved" => true,
                    "is_featured" => true
                        ), false, 1, $page, $perPage);
    }

    public function fetchHot($page = 0, $perPage = 5) {
        $sql = "SELECT gallery_item.id , gallery_item.approved, vote.points " .
                "FROM gallery_item LEFT OUTER JOIN (" .
                "SELECT gallery_id, CAST(SUM(point) AS SIGNED) AS points FROM gallery_vote GROUP BY gallery_id) vote ON gallery_item.id = vote.gallery_id WHERE gallery_item.is_deleted = 0 AND gallery_item.is_approved = 1 ORDER BY CASE WHEN points < 0 THEN 1 ELSE 0 END,points DESC, gallery_item.approved DESC LIMIT " . ($page * $perPage) . ", " . $perPage;
        $query = $this->db->query($sql);
        $resArr = Array();
        foreach ($query->result() as $res) {
            array_push($resArr, $this->findById($res->id));
        }
        return $resArr;
    }

    public function fetchRecent($page = 0, $perPage = 5) {
        $this->orders = Array(
            Array(
                "by" => "approved",
                "opt" => "desc"
            )
        );
        return $this->findAll(Array(
                    "is_approved" => true
                        ), false, 1, $page, $perPage);
    }

    public function fetchPending() {
        return $this->findAll(Array(
                    "is_approved" => false
        ));
    }

    public function fetchHistory() {
        $uid = $this->curUserId();
        $this->db->select("gallery_item.id");
        $this->db->from("gallery_item");
        $this->db->join("image", "image.id = gallery_item.image_id", "left outer");
        $this->db->join("video", "gallery_item.video_id = video.id", "left outer");
        $this->db->where(
                "gallery_item.is_deleted = 0 AND ((gallery_item.type = 'IMG' AND image.uploader_id = '" . $uid . "')"
                . " OR (gallery_item.type = 'VID' AND video.uploader_id = '" . $uid . "'))"
        );
        $this->db->order_by("id", "desc");
        $query = $this->db->get();
        $resArr = Array();

        foreach ($query->result() as $res) {
            array_push($resArr, $this->findById($res->id));
        }

        return $resArr;
    }

}